package service

import (
	"encoding/json"
	r "gitee.com/nanakura/go-ramda"
	"gitee.com/nanakura/h-scraper/internal/global"
	"gitee.com/nanakura/h-scraper/internal/model"
	"log"
	"os"
)

func mapSourceModelToMapper(sourceModel model.SourceModel) map[string]any {
	res := make(map[string]any)
	res["name"] = sourceModel.Name
	res["url"] = sourceModel.Url
	titleTableSelectors := make(map[string]any)
	titleTableSelectors["title_url"] = sourceModel.TitleTableSelectors.TitleUrl
	titleTableSelectors["title_text"] = sourceModel.TitleTableSelectors.TitleText
	titleTableSelectors["pagination_active"] = sourceModel.TitleTableSelectors.PaginationActive
	titleTableSelectors["pagination_url"] = sourceModel.TitleTableSelectors.PaginationUrl
	titleTableSelectors["pagination_text"] = sourceModel.TitleTableSelectors.PaginationText
	titleTableSelectors["category_url"] = sourceModel.TitleTableSelectors.CategoryUrl
	titleTableSelectors["category_text"] = sourceModel.TitleTableSelectors.CategoryText
	res["title_table_selectors"] = titleTableSelectors
	contentSelectors := make(map[string]any)
	contentSelectors["img_url"] = sourceModel.ContentSelectors.ImgUrl
	contentSelectors["text"] = sourceModel.ContentSelectors.Text
	res["content_selectors"] = contentSelectors
	return res
}

func GetSourcesContentHandler() (res []map[string]any, err error) {
	jsonData, err := os.ReadFile("config/sources.json")
	if err != nil {
		return
	}
	var sources model.SourcesContent
	err = json.Unmarshal(jsonData, &sources)
	if err != nil {
		return
	}
	res = r.Map(mapSourceModelToMapper)(sources.Sources)
	return
}

func LoadSourceConfigFromJsonFile(filePath string) (err error) {
	jsonData, err := os.ReadFile(filePath)
	if err != nil {
		log.Println(err)
		return
	}
	sourcesContent := new(model.SourcesContent)
	err = json.Unmarshal(jsonData, sourcesContent)
	sources := sourcesContent.Sources
	for _, source := range sources {
		err = global.DB.Save(&source).Error
		if err != nil {
			log.Println(err)
			return
		}
	}
	return
}
